<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    v-if="load"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1000"
    @close="close"
    :z-index="2000"
  >
    <div class="flex justify-end" v-if="is_coefficient">
      <el-form-item class="mr-2" label="任务质量">
        <el-select class="w-full" v-model="form.task_quality" placeholder="请选择">
          <el-option
            v-for="item in options['assignment.ImagesAssignment']?.[0].taskQualityText"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item class="mr-2" label="目标套数">
        <el-input
          v-model="form.converted_quantity"
          placeholder="请输入"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
        ></el-input>
      </el-form-item>
      <el-form-item label="激励套数">
        <el-input
          v-model="form.incentive_number"
          placeholder="请输入"
          oninput="value=value.replace(/[^\d.]/g, '').replace(/(\.\d{3}).+/, '$1').replace(/(\.\d{2})\d+/, '$1')"
        ></el-input>
      </el-form-item>
    </div>
    <vxe-table
      :data="images_tag"
      style="width: 100%"
      :summary-method="getSummaries"
      show-summary
    >
      <vxe-column field="tag_type" title="标签类型" width="80">
        <template #default="{ row }">
          {{ row.images_tag?.tag_type == 1 ? "图片绩效" : "图片任务" }}
        </template>
      </vxe-column>
      <vxe-column field="tag_name" title="标签名称" width="120">
        <template #default="{ row }">
          {{ row.images_tag?.tag_name }}
        </template>
      </vxe-column>
      <vxe-column field="person" title="绩效人员" width="120">
        <template #default="{ row }">
          {{ row.username }}
        </template>
      </vxe-column>
      <vxe-column field="opearn" title="图片">
        <template #default="{ row }">
          <div class="flex flex-wrap">
            <div v-for="(item, index) in row.img" :key="index">
              <VImageSrc
                width="40"
                height="40"
                :src="item"
                :preview="false"
                @click="showImage(item, row.img)"
              >
              </VImageSrc>
            </div>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="tag_count" title="数量" width="80">
        <template #default="{ row }">
          {{ row.tag_count || 1 }}
        </template>
      </vxe-column>
      <vxe-column field="score" title="单个标签分值" width="120" v-if="!is_coefficient">
      </vxe-column>
      <vxe-column field="" title="系数" width="120" v-if="is_coefficient">
        <template #default="{ row }">
          <template v-if="types == 'view'">{{ row.mode_three_coefficient }}</template>
          <el-select
            v-else
            v-model="row.mode_three_coefficient"
            collapse-tags
            placeholder="请选择"
            clearable
            @change="changeCoefficient($event, row)"
            allow-create
            filterable
          >
            <el-option
              v-for="item in options['assignment.ImagesTag']?.[0].coefficientText"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </template>
      </vxe-column>
      <vxe-column field="total" title="总分数" width="80"></vxe-column>
    </vxe-table>
    <template v-if="types == 'score' && !is_coefficient">
      <el-form class="mt-4" label-position="top">
        <el-row :gutter="21">
          <el-col :span="12">
            <el-form-item label="设计评分">
              <el-input v-model="form.design_score" placeholder="设计评分"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平均分">
              <el-input :value="computedScore()" placeholder="平均分" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="运营评分">
              <el-table :data="form.operator_data" style="width: 100%">
                <el-table-column
                  prop="operator_user_id_text"
                  label="运营人员"
                ></el-table-column>
                <el-table-column prop="score" label="评分">
                  <template #default="{ row }">
                    <el-input v-model="row.score" placeholder="输入评分"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #footer>
      <el-checkbox
        v-if="types != 'view'"
        v-model="form.is_notice"
        :true-label="1"
        :false-label="0"
        >通知运营评分</el-checkbox
      >
      <el-button class="ml-5" @click="close">关闭</el-button>
      <el-button type="primary" @click="serveFun" v-if="types == 'score'">保存</el-button>
    </template>
  </el-dialog>
  <DialogImage ref="DialogImageRef"></DialogImage>
</template>
<script name="pictureDialog" setup>
import { reactive, toRefs } from "vue";
import { setScore, setCoefficient, getTaskTagList } from "../api/index.js";
import VImageSrc from "@/components/Image/index.vue";
import { ElMessage } from "element-plus";
import DialogImage from "@/components/DialogImage/index.vue";
import { photoSort01 } from "@/utils/index";

const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const { options } = toRefs(props);

const data = reactive({
  dialogVisible: false,
  title: "",
  types: null,
  form: {
    task_quality: null,
  },
  images_tag: [],
  is_coefficient: 0,
  load: false,
});

const { dialogVisible, title, types, form, images_tag, is_coefficient, load } = toRefs(
  data
);

const operationType = new Map([
  ["view", "标签查看"],
  ["score", "评分"],
]);

const open = async (type, row, coefficient = 0) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  is_coefficient.value = coefficient;
  form.value.design_score = row.design_score;
  form.value.operator_data = row.images_review_record;
  form.value.converted_quantity = row.converted_quantity;
  form.value.incentive_number = row.incentive_number;
  if (is_coefficient.value) {
    form.value.task_quality = row.task_quality;
  }
  title.value = operationType.get(type);
  types.value = type;
  form.value.task_id = row.id;
  getList(row.id);
  dialogVisible.value = true;
};

const getList = async (taskId) => {
  try {
    const res = await getTaskTagList({
      taskId,
    });
    images_tag.value = res.data.map((i) => {
      i.score = i.images_tag?.score;
      if (is_coefficient.value) {
        i.total = Number((i.tag_count || 1) * i.mode_three_coefficient).toFixed(2);
      } else {
        i.total = Number((i.tag_count || 1) * i.score).toFixed(2);
      }
      return i;
    });
  } catch (e) {
    throw Error(e);
  }
};

const changeCoefficient = (value, row) => {
  const regExp = /^-?\d+(\.\d+)?$/;
  if (!regExp.test(value) && value) {
    ElMessage.error("请输入整数或小数");
    row.mode_three_coefficient = null;
  }
  calculate();
};

const calculate = () => {
  images_tag.value.forEach((i) => {
    i.total = Number((i.tag_count || 1) * i.mode_three_coefficient).toFixed(2);
  });
};

const computedScore = () => {
  const design_score = Number(form.value.design_score || 0);
  const operator_data = form.value.operator_data || [];
  let totalScore = design_score;
  let count = 0;
  if (design_score != 0 && design_score !== "" && design_score !== null) {
    count++;
  }
  for (let i = 0; i < operator_data.length; i++) {
    if (
      operator_data[i].score != 0 &&
      operator_data[i].score !== "" &&
      operator_data[i].score !== null
    ) {
      totalScore += Number(operator_data[i].score);
      count++;
    }
  }

  return count ? Number((totalScore / count).toFixed(2)) : "0.00";
};

const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "汇总";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      const sum = values.reduce((prev, curr) => {
        const value = Number(curr);
        return !Number.isNaN(value) ? prev + value : prev;
      }, 0);
      sums[index] = Number(sum.toFixed(2));
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

const close = () => {
  form.value = {};
  dialogVisible.value = false;
};

const serveFun = async (type) => {
  if (is_coefficient.value) {
    if (images_tag.value.length == 0) {
      ElMessage.error("暂无可评分数据");
      return;
    }
    try {
      const coefficientData = [];
      images_tag.value.forEach((i) => {
        if (i.mode_three_coefficient && i.images_tag.tag_type == 1) {
          coefficientData.push({
            taskTagId: i.img_tag_ids,
            modeThreeCoefficient: i.mode_three_coefficient,
            tag_type: i.images_tag.tag_type,
          });
        } else if (i.mode_three_coefficient && i.images_tag.tag_type == 2) {
          coefficientData.push({
            taskTagId: i.task_tag_ids,
            modeThreeCoefficient: i.mode_three_coefficient,
            tag_type: i.images_tag.tag_type,
          });
        }
      });
      const res = await setCoefficient({
        coefficientData,
        converted_quantity: form.value.converted_quantity,
        incentive_number: form.value.incentive_number,
        task_quality: form.value.task_quality,
        id: form.value.task_id,
      });
      ElMessage.success("操作成功");
      emit("query");
      close();
    } catch (e) {
      throw Error(e);
    }
  } else {
    try {
      const res = await setScore(form.value);
      ElMessage.success("操作成功");
      emit("query");
      close();
    } catch (e) {
      throw Error(e);
    }
  }
};

const DialogImageRef = ref();
const showImage = (row, list) => {
  let newList = [];
  list.forEach((i) => {
    newList.push({
      image_link: i,
    });
  });
  DialogImageRef.value.open(photoSort01({ image_link: row }, newList));
};

defineExpose({ open, close });

const emit = defineEmits(["query"]);
</script>
